package com.Spring.SpringSpms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import com.Spring.SpringSpms.model.StoryPoints;

public class StoryPointsDAOImpl implements StoryPointsDAO{

	private JdbcTemplate jdbcTemplate;
	public StoryPointsDAOImpl(DataSource dataSource)
	{
		this.jdbcTemplate=new JdbcTemplate(dataSource);
	}
	@Override
	public void saveOrUpdate(StoryPoints storyPoints) {
		// TODO Auto-generated method stub
		
		if (storyPoints.getStory_point_id() > 0) {
			// update
			String sql = "UPDATE storypoints SET story_point=? WHERE story_point_id=?";
			jdbcTemplate.update(sql,storyPoints.getStory_point(),storyPoints.getStory_point_id());
		} else {
			// insert
			String sql = "INSERT INTO storypoints (story_point)"
						+ " VALUES (?)";
			jdbcTemplate.update(sql,storyPoints.getStory_point());
		}
		
	}

	@Override
	public void delete(int storyPointId) {
		// TODO Auto-generated method stub
		String sql = "DELETE FROM storypoints WHERE story_point_id=?";
		jdbcTemplate.update(sql,storyPointId);

		
	}

	@Override
	public StoryPoints get(int storyPointId) {
		// TODO Auto-generated method stub
		String sql = "SELECT * FROM storypoints WHERE story_point_id=" + storyPointId;
		return jdbcTemplate.query(sql, new ResultSetExtractor<StoryPoints>() {

			@Override
			public StoryPoints extractData(ResultSet rs) throws SQLException,
					DataAccessException {
				if (rs.next()) {
					StoryPoints storyPoints = new StoryPoints();
					storyPoints.setStory_point_id(rs.getInt("story_point_id"));
					storyPoints.setStory_point(rs.getInt("story_point"));
					return storyPoints;
				}
				
				return null;
			}
			
		});

	}

	@Override
	public List<StoryPoints> list() {
		// TODO Auto-generated method stub
		String sql = "SELECT * FROM storypoints";
		List<StoryPoints> listStoryPoint = jdbcTemplate.query(sql, new RowMapper<StoryPoints>() {

			@Override
			public StoryPoints mapRow(ResultSet rs, int rowNum) throws SQLException {
				
	
				StoryPoints astoryPoint = new StoryPoints();
				astoryPoint.setStory_point_id(rs.getInt("story_point_id"));
				astoryPoint.setStory_point(rs.getInt("story_point"));
				return astoryPoint;
				
			}
			
		});
		
		return listStoryPoint;
	}
	
}




